<template>
  <div class="ai-qa-page">
    <div class="ai-header">
      <div class="ai-title">
        <el-icon class="ai-icon"><ChatDotRound /></el-icon>
        <h2>AI 法律援助助手</h2>
      </div>
      <div class="ai-status" :class="{ 'online': aiStatus }">
        <el-icon><CircleCheck v-if="aiStatus" /><CircleClose v-else /></el-icon>
        <span>{{ aiStatus ? 'AI服务在线' : 'AI服务离线' }}</span>
      </div>
    </div>

    <div class="qa-container">
      <div class="qa-list" ref="chatContainer">
        <div v-if="qaList.length === 0" class="empty-state">
          <el-icon class="empty-icon"><ChatDotRound /></el-icon>
          <p>欢迎使用AI法律援助助手</p>
          <p class="sub-text">我可以帮助您解答法律相关问题，请开始提问吧！</p>
        </div>
        
        <div v-for="(item, idx) in qaList" :key="idx" class="qa-dialog">
          <div class="qa-bubble-row user-row">
            <div class="qa-bubble user-bubble">
              <div class="message-content">{{ item.question }}</div>
              <div class="message-time">{{ formatTime(item.timestamp) }}</div>
            </div>
          </div>
          <div class="qa-bubble-row ai-row">
            <div class="qa-bubble ai-bubble">
              <div class="ai-avatar">
                <el-icon><User /></el-icon>
              </div>
              <div class="message-content">
                <div v-if="item.loading" class="loading-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <div v-else v-html="formatMessage(item.answer)"></div>
              </div>
              <div class="message-time">{{ formatTime(item.timestamp) }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="qa-input-container">
        <div class="qa-input-row">
          <el-input 
            v-model="question" 
            placeholder="请输入您的法律问题..." 
            @keyup.enter="sendQuestion"
            :disabled="loading"
            type="textarea"
            :rows="2"
            resize="none"
            class="question-input"
          />
          <el-button 
            type="primary" 
            @click="sendQuestion" 
            :loading="loading"
            :disabled="!question.trim()"
            class="send-btn"
          >
            <el-icon v-if="!loading"><Promotion /></el-icon>
            <span>{{ loading ? '思考中...' : '发送' }}</span>
          </el-button>
        </div>
        <!-- 快速提问区域已彻底删除 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { ChatDotRound, CircleCheck, CircleClose, User, Promotion } from '@element-plus/icons-vue'
import { chatWithAI, getAIStatus, mockAIResponse } from '@/api/ai'

const question = ref('')
const qaList = ref([])
const loading = ref(false)
const aiStatus = ref(false)
const chatContainer = ref(null)

// 彻底删除 quickQuestions 相关内容

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 格式化消息内容（支持换行）
const formatMessage = (message) => {
  if (!message) return ''
  return message.replace(/\n/g, '<br>')
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 检查AI服务状态
const checkAIStatus = async () => {
  try {
    const result = await getAIStatus()
    aiStatus.value = result.code === 200
  } catch (error) {
    aiStatus.value = false
    console.error('AI服务状态检查失败:', error)
  }
}

// 发送问题
const sendQuestion = async () => {
  if (!question.value.trim() || loading.value) return
  
  const userQuestion = question.value.trim()
  const timestamp = new Date()
  
  // 添加用户问题到列表
  qaList.value.push({
    question: userQuestion,
    answer: '',
    timestamp,
    loading: true
  })
  
  // 清空输入框
  question.value = ''
  loading.value = true
  
  // 滚动到底部
  await scrollToBottom()
  
  try {
    // 调用AI API
    let response
    if (aiStatus.value) {
      // 使用真实API
      response = await chatWithAI(userQuestion, qaList.value.slice(0, -1))
    } else {
      // 使用模拟API
      response = await mockAIResponse(userQuestion)
    }
    
    // 更新最后一条消息
    const lastMessage = qaList.value[qaList.value.length - 1]
    lastMessage.answer = response.data || '抱歉，AI暂时无法回答您的问题，请稍后重试。'
    lastMessage.loading = false
    
  } catch (error) {
    console.error('AI对话失败:', error)
    const lastMessage = qaList.value[qaList.value.length - 1]
    lastMessage.answer = '抱歉，服务暂时不可用，请稍后重试。'
    lastMessage.loading = false
    ElMessage.error('AI服务暂时不可用，请稍后重试')
  } finally {
    loading.value = false
    await scrollToBottom()
  }
}

// 监听对话列表变化，自动滚动
watch(qaList, () => {
  scrollToBottom()
}, { deep: true })

// 组件挂载时检查AI状态
onMounted(() => {
  checkAIStatus()
})
</script>

<style scoped>
.ai-qa-page {
  width: 1100px;
  max-width: none;
  margin: 20px auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
  overflow: hidden;
  padding-top: 47px;
}

.ai-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.ai-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.ai-icon {
  font-size: 24px;
}

.ai-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.ai-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  opacity: 0.9;
}

.ai-status.online {
  color: #67c23a;
}

.qa-container {
  display: flex;
  flex-direction: column;
  height: 600px;
}

.qa-list {
  flex: 1;
  padding: 20px 24px;
  overflow-y: auto;
  background: #f8f9fa;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-state p {
  margin: 8px 0;
  font-size: 16px;
}

.sub-text {
  font-size: 14px !important;
  opacity: 0.8;
}

.qa-dialog {
  margin-bottom: 20px;
}

.qa-bubble-row {
  display: flex;
  margin-bottom: 8px;
}

.user-row {
  justify-content: flex-end;
}

.ai-row {
  justify-content: flex-start;
}

.qa-bubble {
  max-width: 75%;
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.6;
  word-break: break-word;
  position: relative;
}

.user-bubble {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom-right-radius: 6px;
}

.ai-bubble {
  background: white;
  color: #333;
  border: 1px solid #e4e7ed;
  border-bottom-left-radius: 6px;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.ai-avatar {
  width: 24px;
  height: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  flex-shrink: 0;
  margin-top: 2px;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
  margin-top: 4px;
}

.loading-dots {
  display: flex;
  gap: 4px;
  align-items: center;
}

.loading-dots span {
  width: 6px;
  height: 6px;
  background: #909399;
  border-radius: 50%;
  animation: loading 1.4s infinite ease-in-out;
}

.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes loading {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.qa-input-container {
  padding: 20px 24px;
  background: white;
  border-top: 1px solid #e4e7ed;
}

.qa-input-row {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.question-input {
  flex: 1;
}

.question-input :deep(.el-textarea__inner) {
  border-radius: 12px;
  resize: none;
  font-size: 14px;
}

.send-btn {
  border-radius: 12px;
  padding: 12px 20px;
  height: auto;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 滚动条样式 */
.qa-list::-webkit-scrollbar {
  width: 6px;
}

.qa-list::-webkit-scrollbar-track {
  background: transparent;
}

.qa-list::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.qa-list::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.quick-questions,
.quick-label,
.quick-btn {
  display: none !important;
}
</style> 